package com.teach;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;

public class CalendarTest {

	public static void main(String[] args) {
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
		Calendar c = Calendar.getInstance();//简单工厂模式
		System.out.println(c);
		//Calender -> Date
		Date d1 = c.getTime();
		System.out.println(format.format(d1));
		long ms = c.getTimeInMillis();//获取距离毫秒
		System.out.println(ms);
		Date d2 = new Date(ms);
		System.out.println(format.format(d2));
		
		//Date -> Calender
		Calendar c1 = Calendar.getInstance();
		c1.setTime(d1);
		Calendar c2 = Calendar.getInstance();
		c2.setTimeInMillis(ms);
		
		//**获取各时间段**
		System.out.println("年："+c.get(Calendar.YEAR));
		System.out.println("月："+c.get(Calendar.MONTH));//+1 0-11
		System.out.println("日："+c.get(Calendar.DATE));
		System.out.println("时："+c.get(Calendar.HOUR));//0-11
		System.out.println("时："+c.get(Calendar.HOUR_OF_DAY));//0-23
		System.out.println("上下午:"+(c.get(Calendar.AM_PM)==Calendar.AM));//0-1 AM:0 PM:1
		System.out.println("分："+c.get(Calendar.MINUTE));
		System.out.println("秒："+c.get(Calendar.SECOND));
		System.out.println("毫秒："+c.get(Calendar.MILLISECOND));
		System.out.println("星期："+c.get(Calendar.DAY_OF_WEEK));//1-7 日-六
		
		//清理//只能清理,分,秒,毫秒
		System.out.println(format.format(c.getTime()));
		c.clear();
		System.out.println(format.format(c.getTime()));//1970-01-01 00:00:00.000
		c.setTimeInMillis(ms);
		c.clear(Calendar.SECOND);
		c.clear(Calendar.MILLISECOND);
		c.clear(Calendar.MINUTE);
//		c.clear(Calendar.HOUR_OF_DAY);//没有清理
		c.clear(Calendar.HOUR);
		c.clear(Calendar.DATE);
		
		System.out.println(format.format(c.getTime()));
		
		//设置
		c.set(2011, 11, 11, 11, 11, 11);//2011-12-11 11:11:11.000
		System.out.println(format.format(c.getTime()));
		c.clear();
		c.set(2011, 10, 11, 11, 11);//2011-11-11 11:11:00.000
		System.out.println(format.format(c.getTime()));
		c.clear();
		c.set(2011, 10, 11);//2011-11-11 00:00:00.000
		System.out.println(format.format(c.getTime()));
		c.set(Calendar.HOUR, 15);
		c.set(Calendar.MILLISECOND, 999);
		c.set(Calendar.MONTH,1);
		System.out.println(format.format(c.getTime()));//2011-02-11 15:00:00.999
		//异常设置:自动调整
		c.set(Calendar.MONTH,12);
		c.set(Calendar.HOUR,59);
		System.out.println(format.format(c.getTime()));//2011-02-11 15:00:00.999
		c.set(2021, 2,0);
		System.out.println(format.format(c.getTime()));//2021-02-28 23:00:00.999
	
		//加减
		c.add(Calendar.DATE, 2);//+2天
		c.add(Calendar.HOUR, -5);//-5小时
		System.out.println(format.format(c.getTime()));
		
		//**时区**
		int timeOffset = c.get(Calendar.ZONE_OFFSET);
		System.out.println(timeOffset);//时区偏差毫秒数
		TimeZone tz = TimeZone.getTimeZone("America/Los_Angeles");
		c.setTimeZone(tz);
		format.setTimeZone(tz);
		System.out.println(format.format(c.getTime()));
		
	}
}
